const BookApi = require("../../api/BookApi")
const UserApi = require('../../api/UserApi')
// pages/book-read/book-read.js
Page({
book:{
  book_id:0,
  chapter_id:0
},
chapter_id:0,
book_id:0,
  /**
   * 页面的初始数据
   */
  data: {
    showSetting:false,
    balance:0,
    chapter: {
      book_id:0,
      chapter_id:0,
      price:0,
      lock:false,
      content:"",
      title:""
      
    }
  },
hideSetting:function() {
  this.setData({
    showSetting:false
  });
},
onClickOpenChapters:function() {
  wx.navigateTo({
    events:{
      readChapter:chapter_id=>{
        console.log("重新加载chapter:"+chapter_id)
        this.loadChapter(this.book_id,chapter_id)
      }
    },
    url: '/pages/chapter-list/chapter-list?book_id='+this.book_id,
  })
},
buyChapter:function() {
  BookApi.buyChapter(this.book_id,this.chapter_id).then(res=>{
    console.log("购买成功!");
    this.loadChapter(this.book_id,this.chapter_id);

  })
  .catch(err=>{
    console.log("购买失败!")
  })
},
onClickBuyChapter:function() {
    wx.showModal({
      title:"提示",
      content:"是否花费"+this.data.chapter.price+"购买章节?",
      cancelColor: 'cancelColor',
      success:(res)=> {
        if(res.confirm) {
          this.buyChapter()
        }
        else if(res.cancel) {

        }
      }
    })
},
onClickPanel:function() {
  console.log("click panel:")
  this.setData({
    showSetting:!this.data.showSetting
  })
},
loadChapter:function(book_id,chapter_id) {
  BookApi.getChapterContent(book_id,chapter_id).then(res=>{
      console.log(res)
      this.setData({
        chapter:res.data
      });
      if(this.data.chapter.lock) {
        this.updateUserBalance();
      }
  })
  .catch(err=>{
  });
  this.chapter_id = chapter_id;
  this.book_id = book_id;
},
//  未解锁章节时显示用户余额
updateUserBalance:function() {
  UserApi.getUserProfile().then(res=>{
    let coin =  res.data.coin;
    console.log("update coin:"+coin);
    this.setData({
      balance:coin
    })
  })
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.book_id = options.book_id;
      this.chapter_id = options.chapter_id;
    this.loadChapter(this.book_id,this.chapter_id);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})